package com.w4cms.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.w4cms.utils.PasswordUtil;
import com.w4cms.utils.Tools;

public class SysUser extends Model<SysUser> {
	
	private static final long serialVersionUID = 7466342087988898788L;
	public static final SysUser dao = new SysUser();
	
	/**
	 * 用户登录验证
	 * @param username
	 * @param password
	 * @return
	 */
	public SysUser login(String username,String password){
		SysUser u = dao.findFirst("select * from sys_user where (username=? or email=?) and status=0", username,username);
		if(u==null) return null;
		String pwd = u.getStr("password");
		if(!PasswordUtil.verify(password, pwd)) return null;
		return u;
	}
	/**
	 * 添加用户
	 * @return
	 */
	public boolean saveUser(){
		return this.set("create_time", new Date()).set("update_time", new Date()).save();
	}
	/**
	 * 更新修改用户信息
	 * @return
	 */
	public boolean updateUser(){
		return this.set("update_time", new Date()).update();
	}
	/**
	 * 查询用户
	 * @param pageNumber
	 * @param pageSize
	 * @param search
	 * @param roleId
	 * @return
	 */
	public Page<SysUser> searchUsers(int pageNumber, int pageSize,String search,String roleId){
		final List<Object> paras = new ArrayList<Object>(); 
		String select = "select u.id,username,email,sex,status,role_id,u.last_login,u.create_time,u.update_time,r.name as role_name";
		StringBuffer sqlExceptSelect = new StringBuffer(" from sys_user u left join sys_role r on u.role_id=r.id where 1=1 ");
		if(!Tools.isEmpty(search)){
			sqlExceptSelect.append("and (username like ? or email like ?) ");
			paras.add("%"+search+"%");
			paras.add("%"+search+"%");
		}
		if(!Tools.isEmpty(roleId) && !"0".equals(roleId)){
			sqlExceptSelect.append("and u.role_id=?");
			paras.add(roleId);
		}
		return dao.paginate(pageNumber, pageSize, select, sqlExceptSelect.toString(), paras.toArray());
	}
	
	
	/**
	 * 关联角色
	 * @return
	 */
	public SysRole getRole(){
		return SysRole.dao.findById(get("role_id"));
	}
	
	public Map<String,Object> getMap(){
		return this.getAttrs();
	}
}
